package net.labdemo.service.impl;

import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import net.labdemo.dao.UserDao;
import net.labdemo.entity.User;
import net.labdemo.service.UserService;
@Service
public class UserServiceImpl implements UserService {
	@Autowired
	private UserDao userDao;
	
	@Override
	public long register(User u) {
		// TODO Auto-generated method stub
		//初始
		String userSalt=RandomStringUtils.randomAlphanumeric(12);
		long uuid=UUID.randomUUID().getMostSignificantBits();
		//密码
		String inputPswd=u.getInpswd();
		u.setInpswd(null);
		u.setSalt(userSalt);
		String hashPswd=DigestUtils.sha256Hex(inputPswd+"."+userSalt);
		u.setPswd(hashPswd);
		//提练
		u.setBirthday(new Date());
		u.setStatus(1);
		u.setNickname("u"+uuid);
		System.out.println("[S]"+u);
		if(userDao.add(u)==1){
			return u.getId();
		}
		return -1;
	}

	@Override
	public User login(String mail, String inputPswd) {
		// TODO Auto-generated method stub
		String userSalt=userDao.getSalt(mail);
		if(userSalt==null){
			return null;
		}
		String hashPswd=DigestUtils.sha256Hex(inputPswd+"."+userSalt);
		User u=userDao.get(mail, hashPswd);
		return u;
	}

	@Override
	public User get(long id) {
		// TODO Auto-generated method stub
		return userDao.getEntity(id);
	}

	@Override
	public List<User> all() {
		// TODO Auto-generated method stub
		return userDao.all();
	}

}
